#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <string.h>
#include <cstdlib>
#include <memory>
#include <functional>
#include "nocopy.hpp"
#include "InetAddr.hpp"
#include "Common.hpp"
#include "Log.hpp"

using namespace LogModule;
void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    // 1.建立套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error...";
        exit(SOCKET_ERR);
    }
    LOG(LogLevel::DEBUG) << "socket success: " << sockfd;

    // 2.不需要用户bind
    // 3.连接
    InetAddr local(server_ip, server_port);
    int n = ::connect(sockfd, local.GetAddr(), local.GetAddrLen());
    if (n < 0)
    {
        LOG(LogLevel::FATAL) << "connect error...";
        exit(CONNECT_ERR);
    }
    LOG(LogLevel::DEBUG) << "connect success: " << sockfd;

    // 4.链接成功，通信
    while (true)
    {
        std::string client_buffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, client_buffer);
        ssize_t n = write(sockfd, client_buffer.c_str(), client_buffer.size());

        char server_buffer[1024];
        ssize_t size = read(sockfd, server_buffer, sizeof(server_buffer)-1);
        if(size > 0)
        {
            server_buffer[size] = 0;
            std::cout << server_buffer << std::endl;
        }
    }
    close(sockfd);

    return 0;
}